<template>
  <div class="users">
    <div class="navigation">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <el-card class="box-card">
      <div class="top">
        <div class="search-content">
           <!-- v-model="input" -->
          <el-input placeholder="请输入内容"
            v-model="query"
            clearable
            @clear="getUserData"
          ></el-input>
          <!-- <el-input placeholder="请输入内容" v-model="input2"></el-input> -->
          <el-button
            class="search-icon"
            type="primary"
            icon="el-icon-search"
            @click="getUserData"
          ></el-button>
            <!-- @click="search" -->
          
        </div>
        <div class="add-user" @click="dialogFormVisible = true">
          <el-button type="primary">添加用户</el-button>
        </div>
      </div>

      <template>
        <!-- <div v-for="(item,index) in users" :key="index"> -->
        <el-table :data="users" border style="width: 100%">
          <el-table-column label="#" type="index"></el-table-column>
          <el-table-column prop="username" label="姓名"> </el-table-column>
          <el-table-column prop="email" label="邮箱" width="160">
          </el-table-column>
          <el-table-column prop="mobile" label="电话" width="160">
          </el-table-column>
          <el-table-column prop="role_name" width="100" label="角色">
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="changeStatus(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>

          <el-table-column width="165" label="操作">
            <template slot-scope="scope">
              <el-row class="el-row">
                <div class="bottomTip">
                  <el-tooltip
                    class="tip"
                    effect="dark"
                    placement="bottom"
                    :enterable="false"
                  >
                    <div slot="content">编辑</div>
                    <el-button
                      type="primary"
                      icon="el-icon-edit"
                      circle
                      size="medium"
                      @click="showEditDialog(scope.row.id)"
                    ></el-button>
                  </el-tooltip>
                </div>

                <div class="bottomTip">
                  <el-tooltip
                    class="tip"
                    effect="dark"
                    content="删除"
                    placement="bottom"
                    :enterable="false"
                  >
                    <el-button
                      type="danger"
                      icon="el-icon-delete"
                      circle
                      size="medium"
                      @click="deleteUserDialog(scope.row.id)"
                    ></el-button>
                  </el-tooltip>
                </div>

                <div class="bottomTip">
                  <el-tooltip
                    class="tip"
                    effect="dark"
                    content="设置权限"
                    placement="bottom"
                    :enterable="false"
                  >
                    <el-button
                      type="warning"
                      icon="el-icon-setting"
                      circle
                      size="medium"
                      @click="quanxianDialog(scope.row)"
                    ></el-button>
                  </el-tooltip>
                </div>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
        <!-- </div> -->
      </template>

      <div class="bottom">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[1, 2, 3, 4]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增用户 -->
    <el-dialog title="添加用户" :visible.sync="dialogFormVisible"
    @close="closeAdd"
    >
      <el-form
        :model="addUserForm"
        label-width="70px"
        :rules="rules"
        ref="ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="addUserForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addUserForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addUserForm.phone" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button @click="addUser" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑(修改)用户 -->
    <el-dialog title="修改用户" :visible.sync="changeFormVisible">
      <el-form
        :model="changeForm"
        label-width="70px"
        :rules="changeRules"
        ref="changeRuleForm"
      >
        <el-form-item label="用户名">
          <el-input v-model="changeForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="changeForm.email"
            autocomplete="off"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input
            v-model="changeForm.mobile"
            autocomplete="off"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="changeFormVisible = false">取 消</el-button>
        <el-button @click="changeUser" type="primary">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 删除用户对话框 -->
    <el-dialog title="提示" :visible.sync="delUserVisible" width="30%">
      <span>是否删除该用户？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户权限 -->
    <el-dialog title="提示" :visible.sync="quanxianDialogVisible" width="60%">
      <div class="quanxian-item">
        <span>当前的用户：</span>
        <span>{{userInfo.username}}</span>
      </div>
      <div class="quanxian-item">
        <span>当前的角色：</span>
        <span>{{userInfo.role_name}}</span>
      </div>
      <div class="quanxian-item">
        <span>分配新角色：</span>
        <span>
          <el-select v-model="roleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </span>
      </div>
      

      <span slot="footer" class="dialog-footer">
        <el-button @click="quanxianDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="changeQuanxian">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>


<script>
import {mapState} from 'vuex';
export default {
  name: "Users",
  data() {
    // 手机号验证
    let checkTel = (rule, value, callback) => {
      // 1开头，第二位可以为3到9之间，总共11位
      let telReg = /^1[3|4|5|6|7|8|9]\d{9}$/;
      if (telReg.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法手机号码,1开头，第二位为3~9之间，共11位"));
    };
    return {
      input: "",
      value: true,
      pageValue: "",

      // 用户数据列表
      userList: [],
      // 当前页面
      pageNum: 1,
      // 每页显示多少条数据
      pagesize: 4,
      // 数据总数
      total: 0,
      users: [],

      // 新增用户对话框显示隐藏
      dialogFormVisible: false,
      addUserForm: {
        username: "",
        password: "",
        email: "",
        phone: "",
      },
      rules: {
        username: [
          {
            required: true,
            message: "用户名不能为空！",
            trigger: "blur",
          },
          {
            min: 2,
            max: 6,
            message: "用户名长度在2~6个字符之间",
            trigger: ["blur", "change"],
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空！",
            trigger: "blur",
          },
          {
            min: 4,
            max: 10,
            message: "密码长度在4~10个字符之间",
            trigger: ["blur", "change"],
          },
        ],
        email: [
          {
            required: true,
            message: "邮箱不能为空！",
            trigger: "blur",
          },
          {
            type: "email",
            message: "邮箱格式不正确！",
            trigger: ["blur", "change"],
          },
        ],
        phone: [
          {
            required: true,
            message: "手机不能为空！",
            trigger: "blur",
          },
          {
            validator: checkTel,
            trigger: ["blur", "change"],
          },
        ],
      },

      // 用户id
      userId: Number,
      roleId: '',

      userInfo: {},

      // 修改用户对话框显示隐藏
      changeFormVisible: false,
      // 修改用户表单
      changeForm: {
        username: "",
        email: "",
        mobile: "",
        userId: "",
      },
      changeRules: {
        email: [
          {
            required: true,
            message: "邮箱不能为空！",
            trigger: "blur",
          },
          {
            type: "email",
            message: "邮箱格式不正确！",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          {
            required: true,
            message: "手机号码不能为空！",
            trigger: "blur",
          },
          {
            validator: checkTel,
            trigger: ["blur", "change"],
          },
        ],
      },

      // 是否显示删除用户的对话框
      delUserVisible: false,
      // 是否显示修改用户权限的对话框
      quanxianDialogVisible: false,
      // qxValue: "",
      roleList:[],

      // 查询参数
      query:''
    };
  },
  computed:{
  },
  created() {
    this.getUserData();
  },
  methods: {
    // 获取用户数据列表
    getUserData() {
      // 
      this.axios({
        method: "get",
        url: "/users",
        params: {
          query: this.query,
          pagenum: this.pageNum,
          pagesize: this.pagesize,
        },
      })
        .then((res) => {
          
          if (res.data.meta.status == 200) {
            this.userList = res.data.data;
            // 

            this.pageNum = this.userList.pagenum;
            this.total = this.userList.total;

            this.users = this.userList.users;
            // 

            // 获取用户id
            for (let i = 0; i < this.users.length; i++) {
              this.userId = this.users[i].id;
              // 
            }
          }
        })
        .catch((err) => {
          
        });
    },

    // 底部页面选择
    handleSizeChange(val) {
      // 每页选择显示几条数据
      // 

      // this.$emit('handleSizeChange',showPageNum);
      this.pagesize = val;
      this.getUserData();
    },
    handleCurrentChange(val) {
      // 当前页
      // 

      // this.$emit('handleCurrentChange',currentPage)
      this.pageNum = val;
      this.getUserData();
    },

    // 添加新用户
    addUser() {
      // 添加新用户前要验证表单格式是否填写正确
      // 
      this.$refs.ruleForm.validate((valid) => {
        // 

        if (valid) {
          // 
          this.axios({
            method: "post",
            url: "/users",
            data: {
              username: this.addUserForm.username,
              password: this.addUserForm.password,
              email: this.addUserForm.email,
              mobile: this.addUserForm.phone,
            },
          })
            .then((res) => {
              // 
              if (res.data.meta.status == 201) {
                this.$message.success("添加用户成功！");
                this.dialogFormVisible = false;

                this.getUserData();
              } else {
                this.$message.error("添加用户失败！");
              }
            })
            .catch((err) => {
              
            });

          // this.addUserForm.username = "";
          // this.addUserForm.password = "";
          // this.addUserForm.email = "";
          // this.addUserForm.phone = "";
        } else {
          
          return false;
        }
      });
    },
    closeAdd(){
      this.$refs.ruleForm.resetFields();
    },

    // 修改用户状态
    changeStatus(userInfo) {
      

      // let uId = userInfo.id;
      // 
      // 

      // let type = userInfo.mg_state;
      // 

      this.axios({
        method: "put",
        url: `users/${userInfo.id}/state/${userInfo.mg_state}`,
        // data:{
        //   uId:userInfo.id,
        //   type:userInfo.mg_state
        // }
      })
        .then((res) => {
          

          if (res.data.meta.status == 200) {
            this.$message.success("修改用户状态成功！");
          } else {
            this.$message.error("修改用户状态失败！");
            return;
          }
        })
        .catch((err) => {
          
        });
    },

    // 根据用户ID进行搜索
    search(userInfo) {
      // userInfo.id = this.input;
      userInfo.id = this.query;
      

      this.axios({
        method: "get",
        // url:'users/:id'
        url: `users/${userInfo.id}`,
        // params:{
        //   query: this.query
        // }
      })
        .then((res) => {
          // 

          if (res.data.meta.status == 200) {
            this.$message.success("查询成功！");
            this.getUserData();
          } else {
            this.$message.error("抱歉！查无此用户！");
          }
        })
        .catch((err) => {
          
        });
    },

    // 展示修改用户信息的对话框
    showEditDialog(userInfo) {
      

      // 
      // 

      this.axios({
        method: "get",
        url: "users/" + userInfo,
        data: {
          //   // id:id
          // email: this.changeForm.email,
          // mobile: this.changeForm.mobile,
        },
      })
        .then((res) => {
          

          if (res.data.meta.status != 200) {
            this.$message.error("查询用户失败");

            // 查询失败则不打开修改对话框
            this.changeFormVisible = false;
          }

          this.changeForm = res.data.data;
          // 
          this.changeForm.userId = this.changeForm.id;
          // 
          this.changeFormVisible = true;
        })
        .catch((err) => {
          
        });
    },
    // 修改用户信息
    changeUser() {
      this.$refs.changeRuleForm.validate(async (valid) => {
        //   

        if (valid) {
          this.axios({
            method: "put",
            url: "users/" + this.changeForm.userId,
            data: {
              email: this.changeForm.email,
              mobile: this.changeForm.mobile,
            },
          })
            .then((res) => {
              

              // 
              // 

              this.$message.success("修改用户信息成功！");
              this.changeFormVisible = false;
              this.getUserData();
            })
            .catch((err) => {
              
            });
        } else {
          
          return false;
        }
      });
    },

    // 显示删除用户的对话框
    deleteUserDialog(id) {
      // 
      // 
      this.delUserVisible = true;
    },
    // 删除用户
    deleteUser() {
      
      this.axios({
        method: "delete",
        url: "users/" + this.userId,
      })
        .then((res) => {
          

          if (res.data.meta.status == 200) {
            this.$message.success("删除成功！");
            this.delUserVisible = false;
            this.getUserData();
          } else {
            this.$message.error("删除失败！");
            return;
          }
        })
        .catch((err) => {
          
        });
    },

    // 显示修改用户权限的对话框
    quanxianDialog(userInfo) {
      this.quanxianDialogVisible = true;

      // 
      this.userInfo = userInfo;
      // 

      let id = this.userInfo.id;
      let username = this.userInfo.username;
      let rolename = this.userInfo.role_name;
      


      this.axios({
        method: "get",
        url: "roles",
      })
        .then((res) => {
          

          if (res.data.meta.status == 200) {
            this.roleList = res.data.data;
            

            for(let i=0;i<this.roleList.length;i++){
               this.roleId = this.roleList[i].id;
              // 
            }

          }
        })
        .catch((err) => {
          
        });
    },
    changeQuanxian() {
      // 
      // 

      this.axios({
        method: "put",
        // url:'users/:id/role',
        url: `users/${this.userInfo.id}/role`,
        data: {
          // id:this.userId,
          rid: this.roleId,
        },
      })
        .then((res) => {
          
          if(res.data.meta.status == 200){
            this.$message.success('设置角色成功！');
            this.quanxianDialogVisible = false;
            this.getUserData();
          }
        })
        .catch((err) => {
          
        });
    },
  },
};
</script>

<style lang="less" scoped>
.users {
  // border: 1px solid #000;
  margin-top: 70px;
  // margin-left: 200px;

}
.box-card {
  // border: 1px solid #000;
  margin-top: 22px;
  .top {
    // border: 1px solid #000;
    display: flex;
    margin-bottom: 16px;
    .search-content {
      display: flex;
    }
    .add-user {
      margin-left: 18px;
    }
  }
  .bottom {
    margin-top: 15px;
  }
}

/deep/ .el-input__inner {
  // border: 1px solid #000;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  outline: none;
}
/deep/ .search-icon {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  background-color: #ccc;
  border-color: #ccc;
}

.el-row {
  // border: 1px solid #000;
  display: flex;
  .bottomTip {
    margin-right: 10px;
  }
}
.quanxian-item {
  // border: 1px solid #000;
  margin-bottom: 22px;
  &:last-child {
    margin-bottom: 0;
  }
}
</style>